package com.yuanduo_app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.baozi.Zxing.ZXingConstants;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.Callback;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppWakeUpAdapter;
import com.fm.openinstall.model.AppData;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import cn.ydxlm.paylib.PayCallback;
import cn.ydxlm.paylib.PayResult;
import cn.ydxlm.paylib.ali.AliPay;
import cn.ydxlm.paylib.consts.PayType;
import cn.ydxlm.paylib.wx.WxPay;
import com.xujl.fastlib.base.BaseView;
import com.xujl.fastlib.base.BindEventBus;
import com.xujl.fastlib.base.IControl;
import com.xujl.fastlib.base.LayoutBuilder;
import com.xujl.fastlib.utils.AppManager;
import com.xujl.fastlib.utils.LogS;
import com.xujl.fastlib.utils.StringUtils;
import com.xujl.fastlib.utils.ToastUtils;
import com.xujl.task.RxLifeList;

import com.yuanduo_app.base.BaseRNActivity;
import com.yuanduo_app.bridge.DataModule;
import com.yuanduo_app.bridge.PayModule;
import com.yuanduo_app.bridge.QrCodeModule;
import com.yuanduo_app.consts.PermissionGroup;
import com.yuanduo_app.consts.RNEvent;
import com.yuanduo_app.db.waterdb.WaterUtils;
import com.yuanduo_app.event.CheckVersionEvent;
import com.yuanduo_app.event.ChooseImageEvent;
import com.yuanduo_app.event.LoadingEvent;
import com.yuanduo_app.event.MainActivityLifeEvent;
import com.yuanduo_app.event.PayEvent;
import com.yuanduo_app.event.PermissionsEvent;
import com.yuanduo_app.event.PhotoQrCodeEvent;
import com.yuanduo_app.manager.RNModuleManager;
import com.yuanduo_app.service.UpdateService;
import com.yuanduo_app.utils.DeviceUtils;
import com.yuanduo_app.utils.ImgHelper;
import com.yuanduo_app.utils.InstallUtils;
import com.yuanduo_app.utils.MapUtils;
import com.yuanduo_app.utils.update.VersionHelper;
import com.yuanduo_app.widget.QRCodeViewManager;
import com.yuanduo_app.window.CommonInfoWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import razerdp.basepopup.BasePopupWindow;

// import com.oblador.vectoricons.VectorIconsPackage;
// import com.facebook.react.ReactPackage;
@BindEventBus
public class MainActivityControl extends BaseRNActivity implements PayCallback, VersionHelper.VersionCheckCallback {
    private static final String TAG = "MainActivityControl";
    private ChooseImageEvent mChooseImageEvent;
    private RxLifeList mRxLifeList = new RxLifeList();
    private CheckVersionEvent mCheckVersionEvent;

    /**
     * Returns the name of the main component registered from JavaScript. This is used to schedule
     * rendering of the component.
     */
    @Override
    protected String getMainComponentName () {
        return "yuanduo_app";
    }

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.MainAppThemeDefault);
        registerUpdateReceiver();
        AliPay.getInstance().setPayCallback(this);
        WxPay.getInstance().setPayCallback(this);
        // 获取唤醒参数
        OpenInstall.getWakeUp(getIntent(), wakeUpAdapter);
        requestRuntimePermissions(PermissionGroup.MUST);
        EventBus.getDefault().post(new MainActivityLifeEvent(MainActivityLifeEvent.ON_CREATE));
    }

    @Override
    protected void permissionsComplete (String[] permissions) {
        super.permissionsComplete(permissions);


        if (permissions == PermissionGroup.MUST) {
            if (!MapUtils.isGpsOpen(this)) {
                return;
            }
            return;
        }
        if (varyPermissions == PermissionGroup.CHECK_VERSION) {
            VersionHelper.newInstance(MainActivityControl.this).checkVersion(MainActivityControl.this, mCheckVersionEvent != null && mCheckVersionEvent.isLoading());
            return;
        }
        EventBus.getDefault().post(new PermissionsEvent(permissions, true));
        if (permissions == PermissionGroup.CAMERA) {
            if (StringUtils.contains(mChooseImageEvent.getType(), "video")) {
                ImgHelper.openGalleryAndVideo(this);
                return;
            }
            ImgHelper.openGallery(this, ImgHelper.REQUEST_CODE_CHOOSE);
        }
    }

    @Override
    protected void init (Bundle savedInstanceState) {
    }

    @Override
    public void onNewIntent (Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法获取
        OpenInstall.getWakeUp(intent, wakeUpAdapter);
    }

    @Override
    protected BaseView createDefaultView () {
        return new BaseView() {
            @Override
            public void init (IControl control) {

            }

            @Override
            public LayoutBuilder configLayout () {
                return super.configLayout().setEnableDataBinding(false).setEnableAutoSetLayout(false);
            }
        };
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate () {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected ReactRootView createRootView () {
                return new RNGestureHandlerEnabledRootView(MainActivityControl.this);
            }
        };
    }

    @Override
    public boolean enableFragmentBack () {
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showLoading (LoadingEvent event) {
        if (event.isShowLoading()) {
            mView.showLoadingWindow();
        } else {
            mView.dismissLoadingWindow();
        }
    }

    @Subscribe
    public void chooseImage (ChooseImageEvent e) {
        mChooseImageEvent = e;
        requestRuntimePermissions(PermissionGroup.CAMERA);
    }

    @Subscribe
    public void onPayEvent (PayEvent event) {
        switch (event.getPayType()) {
            case PayType.TYPE_ALI:
                AliPay.getInstance().pay(this, (String) event.getData("orderInfo"));
                break;
            case PayType.TYPE_WX:
                WxPay.getInstance().pay(this, event.getData());
            default:

                break;

        }
    }

    @Subscribe
    public void onCheckVersionEvent (CheckVersionEvent event) {
        mCheckVersionEvent = event;
        requestRuntimePermissions(PermissionGroup.CHECK_VERSION);
    }

    @Subscribe
    public void onPhotoQrCodeEvent (PhotoQrCodeEvent event) {
        ImgHelper.openGallery(this, ZXingConstants.ScanPhotosRequestCode);
    }

    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImgHelper.REQUEST_CODE_CHOOSE:
                ImgHelper.receiveImageOrVideo(mChooseImageEvent, requestCode, resultCode, data, this, (file, base64, isVideo) -> {
                    DataModule module = RNModuleManager.getInstance().getModule(DataModule.class);
                    if (module != null) {
                        final Callback callback = module.getCallback();
                        if (callback != null) {
                            if (isVideo) {
                                String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());
                                String mimeName = "";
                                if (!TextUtils.isEmpty(extension)) {
                                    //使用系统API，获取MimeTypeMap的单例实例，然后调用其内部方法获取文件后缀名（扩展名）所对应的MIME类型
                                    mimeName = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase()).replace("video/", "");
                                }
                                callback.invoke(Uri.fromFile(file).toString(), base64, "video", mimeName);
                            } else {
                                callback.invoke(Uri.fromFile(file).toString(), base64);
                            }

                        }
                    }
                });
                break;
            case INSTALL_PERMISS_CODE:
                if (resultCode == RESULT_OK) {
                    InstallUtils.installApk(this);
                } else {
                    final CommonInfoWindow infoWindow = new CommonInfoWindow(this,
                            CommonInfoWindow.createBuilder()
                                    .setInfo("请打开应用内安装权限，否则无法安装。\n是否去打开？")
                                    .setRightStr("去设置")
                                    .setLeftStr("取消")
                    );
                    infoWindow.setCallback(code -> {
                        if (code == CommonInfoWindow.RIGHT_BTN) {
                            InstallUtils.jumpInstallPermission(MainActivityControl.this, INSTALL_PERMISS_CODE);
                        }
                    });
                    infoWindow.showPopupWindow();
                }
                break;
            case QrCodeModule.REQUEST_CODE:
                QrCodeModule.onActivityResult(requestCode, resultCode, data);
                break;
            case ZXingConstants.ScanPhotosRequestCode:
                QRCodeViewManager.onPhotoQrCodeResult(data);
                break;
            case MapUtils.PRIVATE_CODE:
                requestRuntimePermissions(PermissionGroup.MUST);
                break;
        }
    }

    @Override
    protected void onResume () {
        super.onResume();
        EventBus.getDefault().post(new MainActivityLifeEvent(MainActivityLifeEvent.ON_RESUME));
        runOnUiThread(() -> {
            WaterUtils.INSTANCE.checkWaterData();
        });

    }

    @Override
    protected void onPause () {
        super.onPause();
        EventBus.getDefault().post(new MainActivityLifeEvent(MainActivityLifeEvent.ON_PAUSE));
    }

    @Override
    protected void onDestroy () {
        EventBus.getDefault().post(new MainActivityLifeEvent(MainActivityLifeEvent.ON_DESTROY));
        mRxLifeList.onDestroy();
        unregisterUpdateReceiver();
        AliPay.getInstance().setPayCallback(null);
        wakeUpAdapter = null;
        super.onDestroy();
    }

    @Override
    public void onSuccess (PayResult result) {
        PayModule module = RNModuleManager.getInstance().getModule(PayModule.class);
        if (module != null) {
            module.sendEvent(RNEvent.PAY_RESULT, "success");
        }
    }

    @Override
    public void onError (PayResult result, String e) {
        PayModule module = RNModuleManager.getInstance().getModule(PayModule.class);
        if (module != null) {
            module.sendEvent(RNEvent.PAY_RESULT, "failed");
        }
    }

    /**
     * 应用安装监听广播
     */
    private BroadcastReceiver mInstallReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive (Context context, Intent i) {
            if (!InstallUtils.haveInstallPermission(MainActivityControl.this)) {
                //权限没有打开则提示用户去手动打开
                InstallUtils.jumpInstallPermission(MainActivityControl.this, INSTALL_PERMISS_CODE);
                return;
            }
            InstallUtils.installApk(MainActivityControl.this);
        }
    };
    private static final int INSTALL_PERMISS_CODE = 989;

    /**
     * 注册应用安装广播
     */
    private void registerUpdateReceiver () {
        try {
            registerReceiver(mInstallReceiver, new IntentFilter(UpdateService.INSTALL_ACTION));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unregisterUpdateReceiver () {
        try {
            unregisterReceiver(mInstallReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    AppWakeUpAdapter wakeUpAdapter = new AppWakeUpAdapter() {
        @Override
        public void onWakeUp (AppData appData) {
            // 打印数据便于调试
            LogS.d("OpenInstall", "getWakeUp : wakeupData = " + appData.toString());
            // 获取渠道数据
            String channelCode = appData.getChannel();
            // 获取绑定数据
            String bindData = appData.getData();
        }
    };


    @Override
    public void onVersionPass () {
        if (mCheckVersionEvent != null && mCheckVersionEvent.isLoading()) {
            ToastUtils.toast("当前已是最新版本");
        }
    }

    @Override
    public void versionIsNew () {
        onVersionPass();
    }

    @Override
    public void onVersionRefuse () {
        AppManager.getAppManager().goSystemHome();
    }

    @Override
    public void onVersionFail () {
        // showCheckVersionFailedWindow();
        ToastUtils.toast("版本更新检测异常，请检查网络");
    }

    public void showCheckVersionFailedWindow () {
        final CommonInfoWindow infoWindow = new CommonInfoWindow(this,
                CommonInfoWindow.createBuilder()
                        .setInfo("网络异常，请确认网络畅通后重启应用")
                        .setSingleBtn(true)
                        .setRightStr("退出")
        );
        infoWindow.setCallback(code -> AppManager.getAppManager().appExit());
        infoWindow.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss () {
                AppManager.getAppManager().appExit();
            }
        });
        infoWindow.showPopupWindow();
    }


    @Override
    public void onBackPressedSupport () {
        AppManager.getAppManager().goSystemHome();
    }

    @Override
    public boolean permissionsRefuseExit () {
        return true;
    }
}
